import { getYMD, getNowFormatDate, getDay } from '../../../../assets/js/util.js'

import echarts from 'echarts'

export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: '',
                uid: ''
            },
            pickerOptions: {
                shortcuts: [{
                    text: '近7天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '近30天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            title: '广告投放概览',
            platForms: [],
            agents: [],
            settlWays: [],
            channels: [],
            loading: false,
            searchable: false,
            ruleForm: {
                date: '',
                platForm: '',
                agent: '',
                settlWay: '',
                channel: ''
            },
            tableHead1: [{
                    "prop": "actEquipment",
                    "label": "激活设备"
                },
                {
                    "prop": "newEquipment",
                    "label": "新增设备"
                },
                {
                    "prop": "newEquipmentRate",
                    "label": "新增设备转化率"
                },
                {
                    "prop": "newAccount",
                    "label": "新增账号"
                },
                {
                    "prop": "newPay",
                    "label": "新增付费金额"
                },
                {
                    "prop": "payRate",
                    "label": "付费率"
                },
                {
                    "prop": "discount",
                    "label": "成本"
                },
                {
                    "prop": "cpa",
                    "label": "CPA"
                },
                {
                    "prop": "roi",
                    "label": "分成后ROL(%)"
                },
            ],
            tableData1: [],
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            // 指定图表的配置项和数据
            // 分小时数据 付费金额
            pay: {
                color: ['#2eb398', '#79bde9', '#9d79d8'],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: []
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'circle',
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'roundRect',
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'triangle',
                }]
            },
            // 实时数据显示
            realLoadShow: false,
        }
    },
    computed: {

    },
    methods: {
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        //初始化
        _init() {
            var arr = ['djCount', 'jhCount', 'addAccountNum', 'amountPaid', 'activationRate', 'addConversionRate', 'CPA', 'daysRetained', 'daysLTV', 'TdjCount', 'TactivationNum', 'Tincome'];
            for (var x = 0; x < arr.length; x++) {
                this[arr[x] + 'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x] + 'Charts'].setOption(this.pay);
            }
            window.addEventListener('resize', function() {
                var resizeArr = ['djCountCharts', 'jhCountCharts', 'addAccountNumCharts', 'amountPaidCharts', 'activationRateCharts', 'addConversionRateCharts', 'CPACharts', 'daysRetainedCharts', 'daysLTVCharts', 'TdjCountCharts', 'TactivationNumCharts', 'TincomeCharts']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        dateChange(val) {
            /*this.date = val;*/
        },
        agentChange() {

        },
        channelChange() {

        },
        settlWayChange() {

        },
        platFormChange() {

        },
        search() {
            /*console.log(this.agents)*/
        },
        handleSizeChange(val) {
            this.pageSize = val;
            /*this.getTableData(this.ruleForm)*/
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            /*this.getTableData(this.ruleForm)*/
        },
        tableControl() {
            this.tableData1 = this.tableData1.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        /*==================获取下拉列表数据========================*/
        getData() {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`, {
                params: { 'ps': `uid=${this.DP.uid}` }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data['res']) === 0) {
                    /*=====获取平台======*/
                    for (var i = 0; i < data.platform.length; i++) {
                        var obj = {};
                        obj.id = data.platform[i];
                        obj.platFormName = data.platform[i];
                        this.platForms.push(obj);
                    }
                    /*=====获取代理商数据======*/
                    for (var i = 0; i < data.agent.length; i++) {
                        var obj = {};
                        obj.id = data.agent[i];
                        obj.agentName = data.agent[i];
                        this.agents.push(obj);
                    }
                    /*=====获取结算方式数据======*/
                    for (var i = 0; i < data.paytype.length; i++) {
                        var obj = {};
                        obj.id = data.paytype[i];
                        obj.settlWayName = data.paytype[i];
                        this.settlWays.push(obj);
                    }
                    /*=====获取渠道名称======*/
                    for (var i = 0; i < data.channelName.length; i++) {
                        var obj = {};
                        obj.id = data.channelName[i];
                        obj.channelName = data.channelName[i];
                        this.channels.push(obj);
                    }
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*====================时间格式化转换函数============================*/
        formatDate(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        },
        /*==================获取表格数据========================*/
        getTableData(data) {
            this.loads();
            let date1 = this.formatDate(this.ruleForm.date[0]);
            let date2 = this.formatDate(this.ruleForm.date[1]);
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `sday=${date1}&eday=${date2}&agent=${data.agent}&platform=${data.platForm}&channelName=${data.channel}&paytype=${data.settlWay}&uid=${this.DP.uid}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data['res']) === 0) {
                    this.tableData1 = [];
                    this.tableData1.push(data.advOverviewData);
                    this.dataTotal = 1;
                    this.tableControl();
                    this.echartsData(data);
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*===========================查询功能===============================*/
        search(data) {
            this.loads();
            let date1 = this.formatDate(this.ruleForm.date[0]);
            let date2 = this.formatDate(this.ruleForm.date[1]);
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `sday=${date1}&eday=${date2}&agent=${data.agent}&platform=${data.platForm}&channelName=${data.channel}&paytype=${data.settlWay}&uid=${this.DP.uid}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data.res) === 0) {
                    if (data.length == 0) {
                        this.errorFun('查询结果为空！')
                    } else {
                        this.tableData1 = [];
                        this.tableData1.push(data.advOverviewData);
                        this.dataTotal = 1;
                        this.tableControl();
                        this.echartsData(data);
                    }
                } else {
                    this.errorFun(data.msg)
                }
            })
        },
        judgeUnderfind(d, key, i) {
            if (d[key][i] == undefined) {
                var data1 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data1 = d[key][i]['jsonStr'];
            }
            return data1
        },
        // 改变表数据
        echartsData(d) {
            // 点击次数获取到数据渲染
            /*var data = d['advChart'][0];*/
            var data = this.judgeUnderfind(d, 'advChart', 0);
            this.djCountCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // 激活次数获取到数据渲染
            /* var data = d['advChart'][1];*/
            var data = this.judgeUnderfind(d, 'advChart', 1);
            this.jhCountCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // 新增账号数获取到数据渲染
            /* var data = d['advChart'][2];*/
            var data = this.judgeUnderfind(d, 'advChart', 2);
            this.addAccountNumCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // 付费金额获取到数据渲染
            /* var data = d['advChart'][3];*/
            var data = this.judgeUnderfind(d, 'advChart', 3);
            this.amountPaidCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // 激活率获取到数据渲染
            /* var data = d['advChart'][4];*/
            var data = this.judgeUnderfind(d, 'advChart', 4);
            this.activationRateCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // 新增转化率获取到数据渲染
            /* var data = d['advChart'][5];*/
            var data = this.judgeUnderfind(d, 'advChart', 5);
            this.addConversionRateCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // CPA获取到数据渲染
            /*var data = d['effectChart'][0];*/
            var data = this.judgeUnderfind(d, 'effectChart', 0);
            this.CPACharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'line',
                    data: data['data'][0]
                }, ]
            });
            // x日留存获取到数据渲染
            /* var data = d['effectChart'][1];*/
            var data = this.judgeUnderfind(d, 'effectChart', 1);
            this.daysRetainedCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                        name: data['names'][0],
                        type: 'line',
                        data: data['data'][0]
                    },
                    {
                        name: data['names'][1],
                        type: 'line',
                        data: data['data'][1]
                    },
                    {
                        name: data['names'][2],
                        type: 'line',
                        data: data['data'][2]
                    },
                ]
            });
            // x日LTV获取到数据渲染
            /* var data = d['effectChart'][2];*/
            var data = this.judgeUnderfind(d, 'effectChart', 2);
            this.daysLTVCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [{
                        name: data['names'][0],
                        type: 'line',
                        data: data['data'][0]
                    },
                    {
                        name: data['names'][1],
                        type: 'line',
                        data: data['data'][1]
                    },
                    {
                        name: data['names'][2],
                        type: 'line',
                        data: data['data'][2]
                    },
                ]
            });
            // TOP指标点击数获取到数据渲染
            /*var data = d['topChart'][0];*/
            var data = this.judgeUnderfind(d, 'topChart', 0);
            this.TdjCountCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    type: 'value',
                },
                yAxis: {
                    type: 'category',
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'bar',
                    data: data['data'][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    },
                }]
            });
            // TOP指标激活数获取到数据渲染
            // var data = d['topChart'][1];
            var data = this.judgeUnderfind(d, 'topChart', 1);
            this.TactivationNumCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    type: 'value',
                },
                yAxis: {
                    type: 'category',
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'bar',
                    data: data['data'][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    },
                }]
            });
            // TOP指标收入数获取到数据渲染
            /*var data = d['topChart'][2];*/
            var data = this.judgeUnderfind(d, 'topChart', 2);
            console.log(data['data'][0]);
            this.TincomeCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    type: 'value',
                },
                yAxis: {
                    type: 'category',
                    data: data['columnkeys']
                },
                series: [{
                    name: data['names'],
                    type: 'bar',
                    data: data['data'][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    },
                }]
            });

        }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
        this.getData();
        this.ruleForm.date = [new Date(new Date().getTime() - 7 * 86400000), new Date()];
        this.getTableData(this.ruleForm);
        this.djCountCharts = echarts.init(document.getElementById('djCount'));
        this.djCountCharts.setOption(this.pay);
        this._init();
    }
}